package org.example.netty.echo;

import com.alibaba.fastjson2.JSONObject;

import org.example.netty.example.SubDeviceData;

import java.nio.charset.Charset;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author liuzefeng 2024/3/18 14:08:30
 */
@Slf4j
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SubDeviceData deviceData = new SubDeviceData();
        deviceData.setUid("CB583A2993F46BA");
        deviceData.setSecond((short)10);
        deviceData.setCmd("DEVICE_DATA");
        deviceData.setToken("722f7317-1f5c-4d2b-b875-42178ad7f559");
        deviceData.setUserName("18059218850");
        ctx.writeAndFlush(JSONObject.toJSONString(deviceData));



//        String message = "netty client";
//        ByteBuf buffer = ctx.alloc().buffer(message.length());
//        buffer.writeBytes(message.getBytes());
//        ctx.writeAndFlush(buffer);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf)msg;
        log.info("channelRead -- client receive msg:{}", buf.toString(Charset.defaultCharset()));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        log.info("channelRead0 -- client receive msg:{}", msg.toString(Charset.defaultCharset()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
